package br.com.winesys.geta.databinding.component.selector;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import br.com.winesys.geta.databinding.component.listeners.SelectionListener;

public final class EnumSelector<Model extends Enum<?>> extends JPanel {

	private ButtonGroup buttonGroup;

	public EnumSelector() {
		setLayout(new FlowLayout(FlowLayout.LEFT, 0, 5));
	}

	public ButtonGroup getButtonGroup() {
		return this.buttonGroup;
	}

	public void setValues(Model[] values) {
		this.removeAll();
		this.buttonGroup = new ButtonGroup();
		JRadioButton[] componentes = new JRadioButton[values.length];
		for (int i = 0; i < values.length; i++) {
			componentes[i] = new JRadioButton();
			this.buttonGroup.add(componentes[i]);
			this.add(componentes[i]);
			componentes[i].putClientProperty("value", values[i]);
			componentes[i].setText(values[i].toString());
			componentes[i].addActionListener(new ActionListener() {

				@SuppressWarnings("unchecked")
				@Override
				public void actionPerformed(ActionEvent evt) {
					for (SelectionListener<Model> listener : EnumSelector.this.listenerList.getListeners(SelectionListener.class)) {
						listener.itemSelected((Model) ((JRadioButton) evt.getSource()).getClientProperty("value"));
					}
				}
			});
		}
		this.buttonGroup.getElements().nextElement().setSelected(true);
	}

	public void addSelectionListener(SelectionListener<Model> listener) {
		this.listenerList.add(SelectionListener.class, listener);
	}

	public void removeSelectionListener(SelectionListener<Model> listener) {
		this.listenerList.remove(SelectionListener.class, listener);
	}

	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		for (Component c : this.getComponents()) {
			c.setFocusable(enabled);
			c.setEnabled(enabled);
		}
	}
}
